/*
+--------------------------------------------------------------------------
|   Mblog [#RELEASE_VERSION#]
|   ========================================
|   Copyright (c) 2014, 2015 mtons. All Rights Reserved
|   http://www.mtons.com
|
+---------------------------------------------------------------------------
*/
package com.mtons.mblog.modules.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mtons.mblog.modules.entity.Say;
import com.mtons.mblog.modules.repository.SayRepository;
import com.mtons.mblog.modules.service.SayService;

@Service
@Transactional(readOnly = true)
public class SayServiceImpl implements SayService {
	@Autowired
	private SayRepository sayRepository;

	@Override
    @Transactional
	public Say say(Say say) {
		Say nsay = new Say();
		nsay.setComment(say.getComment());
		nsay.setLastLogin(new Date());
		return sayRepository.save(nsay);
	}

	@Override
	public Page<Say> paging(Pageable pageable) {
		Page<Say> page = sayRepository.findAll((root, query, builder) -> {
			Predicate predicate = builder.conjunction();
			query.orderBy(builder.desc(root.get("id")));
			return predicate;
		}, pageable);

		List<Say> rets = new ArrayList<>();
		page.getContent().forEach(n -> rets.add(n));
		return new PageImpl<>(rets, pageable, page.getTotalElements());
	}

}
